from fastapi import FastAPI, Request
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse

from app.utils.errors import MyException, UnknowException
from app.utils.response import BaseRes


class ErrorRes(BaseRes):
    pass


def exception_handler(app: FastAPI):
    @app.exception_handler(Exception)
    async def handle_my_exception(request: Request, exc: Exception):
        if isinstance(exc, MyException):
            return JSONResponse(content=jsonable_encoder(ErrorRes(code=exc.code, msg=exc.msg)))
        return JSONResponse(content=jsonable_encoder(ErrorRes(code=UnknowException.code, msg=UnknowException.msg)))
